package com.tdwyz.fictionmanage.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tdwyz.fictionmanage.pojo.*;
import com.tdwyz.fictionmanage.pojo.webNovel.ChapterInfo;
import com.tdwyz.fictionmanage.pojo.webNovel.ContentInfo;
import com.tdwyz.fictionmanage.pojo.webNovel.FictionWeb;
import com.tdwyz.fictionmanage.pojo.webNovel.NovelInfo;
import com.tdwyz.fictionmanage.service.ChapterService;
import com.tdwyz.fictionmanage.service.FictionService;
import com.tdwyz.fictionmanage.utils.ThreadLocalUtil;
import com.tdwyz.fictionmanage.utils.URLUtil;
import org.jsoup.Connection;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 14543
 * @version 1.0
 * @description: TODO
 * @date 2024/7/28 15:48
 */
@RestController
@RequestMapping("/chapter")
public class ChapterController {

    //小说网站
    private final String baseUrl = "http://www.xbiqugu.net";
    //该网站小说的搜索Endpoin
    private final String searchEndpoint = "/modules/article/waps.php";



    @Autowired
    private ChapterService chapterService;

    @Autowired
    private FictionService fictionService;

    /**
     * 新增小说章节
     * @param chapter
     * @return
     */
    @PostMapping("/add")
    public Result insert(@RequestBody Chapter chapter){
        //存在性校验
        Fiction fiction = fictionService.getById(chapter.getFictionId());
        if (fiction == null) {
            return Result.defeat("小说不存在");
        }
        if(ThreadLocalUtil.getUserId() != fiction.getCreateUser()){
            return Result.defeat("不是您的小说，不能添加");
        }

        boolean ret = chapterService.insert(chapter);
        return Result.toAjax(ret);
    }

    /**
     * 展示某小说的全部章节（分页显示）
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public Result list(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize
    ){
        PageBean<Chapter> pageBean = chapterService.list(pageNum,pageSize);
        return Result.success(pageBean);
    }

    /**
     * 获取章节详情（数据回显）
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Result<Chapter> detail(@RequestParam Integer id){

        return Result.success(chapterService.getById(id));
    }

    /**
     * 修改小说某章节内容
     * @param chapter
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody Chapter chapter){
        //存在性校验
        Fiction fiction = fictionService.getById(chapter.getFictionId());
        if (fiction == null) {
            return Result.defeat("小说不存在");
        }

        //存在性校验
        Chapter chapterDb =  chapterService.getById(chapter.getId());
        if (chapterDb == null) {
            return Result.defeat("章节不见了");
        }

        //判断当前文章是否归属当前用户
        Integer userId = ThreadLocalUtil.getUserId();
        if (userId != chapterDb.getCreateUser()) {
            return Result.defeat("修改失败");
        }

        return Result.toAjax(chapterService.update(chapter));
    }

    /**
     * 删除该章节
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        //1 存在性校验
        Chapter chapter = chapterService.getById(id);
        if (chapter == null) {
            return Result.defeat("章节不存在");
        }
        //2 归属问题
        Integer userId = ThreadLocalUtil.getUserId();
        if (userId != chapter.getCreateUser()) {
            return Result.defeat("删除失败");
        }
        //3 删除
        return Result.toAjax (chapterService.delete(id));
    }


    /**
     * 执行搜索并获取结果
     * @param query 搜索关键词
     * @return 小说标题和链接的列表
     * @throws IOException 如果网络连接失败
     */
    @GetMapping("/search")
    public Result searchNovel(
            @RequestParam String query,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) throws IOException {

        List<NovelInfo> novels = new ArrayList<>();

        // 执行搜索请求
        Connection.Response response = Jsoup.connect(baseUrl + searchEndpoint)
                .data("searchkey", query)
                .method(Connection.Method.POST)
                .execute();

        // 解析搜索结果页面
        Document doc = response.parse();
        // 选择表格中的每一行
        Elements rows = doc.select("table.grid tbody tr");

        for (Element row : rows) {
            // 获取每一行中的每一个单元格
            Elements cells = row.select("td");

            if (cells.size() == 4) {
                String novelTitle = cells.get(0).select("a").text();
                String novelUrl = cells.get(0).select("a").attr("href"); // 获取小说链接

                String chapterTitle = cells.get(1).select("a").text();
                String chapterUrl = cells.get(1).select("a").attr("href"); // 获取章节链接
                chapterUrl = baseUrl + chapterUrl;

                String author = cells.get(2).text();
                String date = cells.get(3).text();

                // 存储到字段中
                NovelInfo novelInfo = new NovelInfo(novelTitle, novelUrl, chapterTitle, chapterUrl, author, date);
                novels.add(novelInfo);
            }
        }

        // 使用 PageHelper 分页
        PageHelper.startPage(page, size);
        PageInfo<NovelInfo> pageInfo = new PageInfo<>(novels);

        // 封装到 PageBean
        PageBean<NovelInfo> pageBean = new PageBean<>();
        pageBean.setTotal(pageInfo.getTotal());
        pageBean.setData(pageInfo.getList());

        return Result.success(pageBean);
    }


    /**
     * 从小说分类页面中抓取小说标题和链接
     * @param baseUrl 小说分类页面 URL
     * @return 小说标题和链接的列表
     * @throws IOException 如果网络连接失败
     */
    @GetMapping("/showInfo")
    public Result searchFiction(String baseUrl) throws IOException {

        FictionWeb fictionWeb = new FictionWeb();

        // 解析搜索结果页面
        Document doc = Jsoup.connect(baseUrl).get();

        Element mainInfo = doc.getElementById("maininfo");
        String title = mainInfo.select("#info h1").text();//标题
        String author = mainInfo.select("#info p").first().text().replace("作    者: ", "");//作者
        String latestTime = mainInfo.select("#info p").get(2).text().replace("最后更新: ", "");//最新更新时间
        String latestChapterTitle = mainInfo.select("#info p").get(3).select("a").text();//最新章节
        String latestChapterUrl = mainInfo.select("#info p").get(3).select("a").attr("href");//最新章节地址
        // 获取#intro中的简介
        Element introElement = doc.getElementById("intro");
        String intro = introElement.select("p").get(1).text();
        //小说封面链接
        String imgUrl = doc.select("#fmimg img").attr("src");

        //将数据封装到fictionWeb
        fictionWeb.setTitle(title);
        fictionWeb.setAuthor(author);
        fictionWeb.setLatestTime(latestTime);
        fictionWeb.setLatestChapterTitle(latestChapterTitle);
        fictionWeb.setLatestChapterUrl(latestChapterUrl);
        fictionWeb.setIntroduction(intro);
        fictionWeb.setCoverImage(imgUrl);

        // 根据实际网页结构更新选择器
        Elements chapterElements = doc.select("#list dd a");

        //初始化章节表列表
        fictionWeb.setChapters(new ArrayList<>());

        for (Element chapterElement : chapterElements) {
            String chapterTitle = chapterElement.text();
            // 获取 URL 的主机部分
            baseUrl = URLUtil.getBaseUrl(baseUrl);
            String chapterUrl = baseUrl + chapterElement.attr("href");

            fictionWeb.getChapters().add(new ChapterInfo(chapterTitle, chapterUrl));
        }

        return Result.success(fictionWeb);
    }

    /**
     * 获取章节内容
     * @param url
     * @return
     */
    @GetMapping("/content")
    public Result proxyRequest(@RequestParam String url) {

        ContentInfo contentInfo = new ContentInfo();

        try {
            Document doc = Jsoup.connect(url).get();

            // 提取章节标题
            Element titleElement = doc.selectFirst("div.bookname h1");
            contentInfo.setTitle(titleElement.text());


            //获取内容
            Element contentElement = doc.selectFirst("div#content");
            if (contentElement != null) {
                // 移除 <p> 标签 和 <div id=content_tip>（广告）
                contentElement.select("div#content_tip").remove();
                contentElement.select("p").remove();

                contentInfo.setContent(contentElement.html()); // 设置 HTML 内容

            }

            // 提取链接（上一章、下一章、章节目录）
            Element bottomElement = doc.selectFirst("div.bottem1");
            if (bottomElement != null) {
                Elements links = bottomElement.select("a");
                for (Element link : links) {
                    String href = link.attr("href");
                    String text = link.text();
                    if (text.contains("上一章")) {
                        contentInfo.setPreChapterUrl(href.startsWith("http") ? href : "http://www.xbiqugu.net" + href);
                    } else if (text.contains("下一章")) {
                        contentInfo.setNextChapterUrl(href.startsWith("http") ? href : "http://www.xbiqugu.net" + href);
                    } else if (text.contains("章节目录")) {
                        contentInfo.setChapterDir(href.startsWith("http") ? href : "http://www.xbiqugu.net" + href);
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            return Result.defeat("没找到文章");
        }
        return Result.success(contentInfo);
    }
}
